package org.roan.nettyserver.listener;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.handler.codec.string.StringEncoder;
import org.roan.nettyserver.handler.NettyHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Slf4j
@Component
public class NettyServer implements ApplicationListener<ApplicationStartedEvent> {

    @Value("${netty.port}")
    private int nettyPort;

    @Autowired
    private NettyHandler nettyHandler;

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        InetAddress localHost;
        try {
            localHost = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            throw new RuntimeException("no localhost available", e);
        }

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addFirst(new LoggingHandler());
                        ch.pipeline().addFirst(new StringEncoder());

                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addFirst(new LoggingHandler());
                        ch.pipeline().addLast(nettyHandler);
                    }
                })
                .bind(localHost, nettyPort);
        log.info("server started at port {} successfully", nettyPort);
    }
}
